package com.huluobo.a2307douyindemo.register

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2307douyindemo.R
import com.huluobo.a2307douyindemo.databinding.ActivityRegisterBinding
import com.huluobo.lib_base.mvvm.BaseActivity
import com.huluobo.lib_base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class RegisterActivity : BaseActivity<ActivityRegisterBinding, RegisterViewModel>() {
    override fun initData() {
        vm.registerSuccess.observe(this) {
            ToastUtils.showLong("注册成功")
            finish()
        }
    }

    override fun initView() {
        binding.registerBtn.setOnClickListener {
            val username = binding.registerUsernameEt.text.toString()
            val password = binding.registerPasswordEt.text.toString()
            val rePassword = binding.registerRePasswordEt.text.toString()

            if (username.isNotEmpty() && password.isNotEmpty() && rePassword.isNotEmpty()) {
                if (password == rePassword) {
                    val map = mutableMapOf<String, String>()
                    map[Const.PARAM_USERNAME] = username
                    map[Const.PARAM_PASSWORD] = password
                    map[Const.PARAM_RE_PASSWORD] = rePassword

                    val json = Gson().toJson(map)
                    val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                    vm.register(body)
                } else {
                    binding.registerRePasswordEt.error = "两次密码输入不一致"
                }
            } else {
                binding.registerRePasswordEt.error = "输入项不能为空"
            }
        }
    }
}